package com.business.wechat.handler;

import java.util.Date;
import java.util.Map;

import com.business.system.bean.WxUserBean;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.business.system.service.WxUserService;
import com.business.wechat.service.CoreService;


/**
 * 用户关注公众号Handler
 * <p>
 * Created by FirenzesEagle on 2016/7/27 0027.
 * Email:liumingbo2008@gmail.com
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    protected WxMpConfigStorage configStorage;
    @Autowired
    protected WxMpService wxMpService;
    @Autowired
    protected CoreService coreService;
    @Autowired
    protected WxUserService wxUserService;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        WxMpUser wxMpUser = coreService.getUserInfo(wxMessage.getFromUser(), "zh_CN");
        Service service = new Service();
        try {
            WxUserBean bean = wxUserService.getUserInfoByOpenId(service,wxMpUser.getOpenId());
            //之前已经在平台关注过
            if(bean!=null){
                //设置成关注
                bean.setSubscribe(2);
                bean.setSubscribeTime(new Date());
                DBUtils.update(service,bean);
            }else{
                //新增系统用户
                wxUserService.insertWxUserFromWxMpUser(service,wxMpUser);
            }
            service.commit();
        } catch (Exception e) {
            service.rollback();
            e.printStackTrace();
        }finally {
            service.close();
        }
        WxMpXmlOutTextMessage m
            = WxMpXmlOutMessage.TEXT()
            .content("尊敬的" + wxMpUser.getNickname() + "您好，感谢您的关注！\n" +
                    "申请大果酱代理，日赚500万！全球已有2000万生物加入，可以绕地球88圈！\n" +
                    "加盟大果酱，赢取白富美！")
            .fromUser(wxMessage.getToUser())
            .toUser(wxMessage.getFromUser())
            .build();
        logger.info("subscribeMessageHandler" + m.getContent());
        return m;
    }
}
